// 速率限制
package main

import (
	"fmt"
	"time"
)

func main() {
	//定义一个有5个缓冲区的通道
	requests := make(chan int, 5)

	//将通道填充满
	for i := 1; i <= 5; i++ {
		requests <- i
	}
	close(requests)

	//定义一个每隔200ms就触发的timer
	limiter := time.Tick(1000 * time.Millisecond)

	for req := range requests {
		<-limiter
		fmt.Println("---request---:", req, time.Now())
	}

	//此通道允许最多三个爆发事件
	burstyLimiter := make(chan time.Time, 3)

	//填充通道，表示允许的爆发
	for i := 0; i < 3; i++ {
		burstyLimiter <- time.Now()
	}

	//每200ms尝试添加一个新的值到burstyLimiter中，知道达到3个的限制
	go func() {
		for t := range time.Tick(1200 * time.Millisecond) {
			burstyLimiter <- t
		}
	}()

	//模拟另外五个传入请求
	burstyRequests := make(chan int, 10)
	for i := 1; i <= 10; i++ {
		burstyRequests <- i
	}
	close(burstyRequests)
	for req := range burstyRequests {
		<-burstyLimiter
		fmt.Println("request", req, time.Now())
	}
}
